package com.our.sys.project1.service;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.our.set.service.HzService;
import com.our.sys.project1.dao.PersonDao;
import com.our.sys.project1.entity.Person;

@Service
@Transactional
public class PersonService {

    @Autowired
    private PersonDao personDao;

    @Autowired
    private HzService hzService;

    private static Logger logger = LoggerFactory.getLogger(PersonService.class);

    @Transactional(readOnly = true)
    public Page<Person> query(Page<Person> page, List<PropertyFilter> filters) {
        Page<Person> curPage = personDao.findPage(page, filters);
        return curPage;
    }

    @Transactional(readOnly = true)
    public Person queryById(Long id) {
        return personDao.findOneBy("id", id);
    }

    @Transactional(readOnly = true)
    private Long queryCountByName(String name) {
        Long result = personDao.findUnique("select count(a) from Person a where a.name = ?", name);
        if (null == result) {
            return 0L;
        } else {
            return result;
        }
    }

    public void save(Person person) throws Exception {
        try {
            Map<String, String> map = hzService.getMemo(person.getName());
            person.setPy(map.get("py"));
            person.setWb(map.get("wb"));
            if (null != person.getId()) {
                Person getPerson = this.queryById(person.getId());

                if (queryCountByName(getPerson.getName()).compareTo(1L) > 0) {
                    throw new Exception("已经存在这个操作名称！");
                }

                getPerson.setSex(person.getSex());
                getPerson.setNumber(person.getNumber());
                getPerson.setName(person.getName());
                getPerson.setType(person.getType());
                getPerson.setPy(person.getPy());
                getPerson.setWb(person.getWb());
                personDao.save(getPerson);
            } else {

                if (queryCountByName(person.getName()).compareTo(0L) > 0) {
                    throw new Exception("已经存在这个操作名称！");
                }
                personDao.save(person);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    public void delete(Long id) throws Exception {
        try {
            personDao.delete(id);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }
}
